package com.micai.boss.sms.queue.service;

import com.micai.boss.base.exception.ServiceException;
import com.micai.boss.sms.dto.Message;
import com.micai.boss.sms.provider.SmsProvider;
import com.micai.boss.sms.queue.base.TaskExecuteComponent;
import com.micai.boss.sms.queue.utils.ApplicationUtil;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

/**
 * 描述：
 * <p>
 *
 * @author: 赵新国
 * @date: 2018/4/24 11:35
 */
public class SmsTaskService extends SmsTaskQueueService {

    public SmsTaskService() {
        super();
        // 异常不重试
        RETRY_EXCEPTION = false;
    }

    public static class SmsTask implements TaskExecuteComponent {

        private final static Logger logger = LoggerFactory.getLogger(SmsTask.class);

        private String taskId;

        private Map<String, SmsProvider> smsProvidersMap;

        @Override
        public void setTask(String taskId) {
            this.taskId = taskId;
            this.smsProvidersMap = (Map<String, SmsProvider>) ApplicationUtil.getBeansOfType(SmsProvider.class);
        }

        @Override
        public void execute() {
            Long startTime = System.currentTimeMillis();
            logger.info("[SendSmsTask:{}] start.", taskId);
            try {
                JSONObject json = JSONObject.fromObject(taskId);
                Message message = (Message) json.toBean(json, Message.class);
                SmsProvider smsProvider = this.selectOne(message);
                boolean isSuccess = smsProvider.send(message);
                if(!isSuccess){
                    logger.error("[SendSmsTask:{}] fail.", taskId);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            logger.info("[SendSmsTask:{}] end, time:{}ms", taskId, System.currentTimeMillis() - startTime);
        }

        private SmsProvider selectOne(Message message) {
            Iterator<Map.Entry<String, SmsProvider>> iterator = smsProvidersMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Entry<String, SmsProvider> entry =  iterator.next();
                SmsProvider smsProvider = entry.getValue();
                if (smsProvider.isAvailable(message)) {
                    logger.info("[SendSmsTask providerName:{}]", message.getProviderName());
                    return smsProvider;
                }
            }
            throw new ServiceException("没有这个短信通道:" + message.getProviderName());
        }

    }

}
